import { ResultPage, Card, Switch, Button } from "antd-mobile";
import "./style.css";
import { useSelector, useDispatch } from "react-redux";
import { LoopOutline } from "antd-mobile-icons";
import {cityExchange, citySetIsSpeed} from '../../reducers/citySlice'
import dayjs from 'dayjs' // 专门用来处理时间的工具库
import { useMemo, useState } from "react";
import DatePopup from "./components/DatePopup";
import CityPopup from "./components/CityPopup";

// 得到的是星期几，0是星期天， 1-6是星期一-六
// console.log(dayjs().day())
// console.log(dayjs('2025-10-27').day())

const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

function Home() {
    const citySlice = useSelector((state) => state.citySlice);
    const dispatch = useDispatch();

    const [visible1, setVisible1] = useState(false)
    const [visible2, setVisible2] = useState(false)
    const [type, setType] = useState('')

    const exChangeFN = () => {
        dispatch(cityExchange());
    }

    // 需要优化
    // const dayNum = dayjs(citySlice.date).day();
    // 这里每次这个组件更新都会 执行一次 获取星期的操作，
    // 为了减少这个操作次数可以使用useMemo计算属性优化一下
    const dayNum = useMemo(() => {
        return dayjs(citySlice.date).day();
    }, [citySlice.date]);

    const isSpeedChange = (checked) => {
        dispatch(citySetIsSpeed(checked))
    }


    return (
        <ResultPage
            // icon={<div />}
            status=""
            title="火车票"
            description="边界购票，服务您的每一次出行"
        >
            <Card className="city_box">
                <div className="city_select">
                    <div onClick={() => {
                        setVisible2(true)
                        setType('start')
                    }}>{citySlice.start}</div>

                    <LoopOutline onClick={exChangeFN} />
                    
                    <div onClick={() => {
                        setVisible2(true)
                        setType('end')
                    }} className="city_select_end">{citySlice.end}</div>
                </div>

                <div className="city_date" onClick={() => {
                    setVisible1(true)
                }}>
                    {citySlice.date}
                    <span>{days[dayNum]}</span>
                </div>

                <div className="city_isSpeed">
                    <span>是否只看高铁</span>
                    <Switch checked={citySlice.isSpeed} onChange={isSpeedChange} />
                </div>

                <div className="city_search_btn">
                    <Button block color="primary" size="middle">
                        搜索
                    </Button>
                </div>
            </Card>
            <CityPopup type={type} visible2={visible2} setVisible2={setVisible2}/>
            <DatePopup visible1={visible1} setVisible1={setVisible1} />
        </ResultPage>
    );
}

export default Home;
